/* 封装 axios 用于发送请求 */
import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'

import router from '../router'

const baseURL = 'http://pcapi-xiaotuxian-front-devtest.itheima.net'
let loadingInstance
const request = axios.create({
  baseURL: baseURL,
  timeout: 10000000,
})

request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.userInfo.token) {
      config.headers.Authorization = `Bearer ${userStore.userInfo.token}`
    }
    loadingInstance = ElLoading.service({
      lock: true,
      text: '加载中…',
      background: 'rgba(0,0,0,0.7)',
    })
    return config
  },
  (error) => {
    loadingInstance?.close()
    ElMessage.error(error.message)
    return Promise.reject(error)
  },
)

request.interceptors.response.use(
  (response) => {
    loadingInstance?.close()
    const { data } = response
    if (data.code === '1') {
      return data.result
    }

    ElMessage.error(data.message || '业务错误')
    return Promise.reject(data.message)
  },
  (error) => {
    loadingInstance?.close()
    if (error.status === 401) {
      const route = router.currentRoute.value
      if (route.path !== '/login') {
        ElMessage.error('登录超时')
        router.replace({ path: '/login', query: { redirect: route.fullPath } })
      }
      return
    }
    ElMessage.error(error.message || '网络错误')
    return Promise.reject(error)
  },
)

/* 导出业务方法 */
export const get = (url, params) => request.get(url, { params })

export const postFormUrl = (url, data) =>
  request.post(url, data, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  })

export const postFormData = (url, params) => {
  const fd = new FormData()
  Object.keys(params).forEach((k) => fd.append(k, params[k]))
  return request.post(url, fd)
}

export const postJSON = (url, data) =>
  request.post(url, data, {
    headers: { 'Content-Type': 'application/json;charset=UTF-8' },
  })
export const deletedJson = (url, data) => {
  request.delete(url, { data }).then((r) => {
    ElMessage.error(r.statusText)
  })
}
export const deletedFormUrl = (url, params) => {
  return request.delete(url, {
    params,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  })
}

export const putJSON = (url, data) =>
  request.put(url, data, {
    headers: { 'Content-Type': 'application/json;charset=UTF-8' },
  })

export const putFormUrl = (url, data) =>
  request.put(url, data, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  })

export const putFormData = (url, params) => {
  const fd = new FormData()
  Object.keys(params).forEach((k) => fd.append(k, params[k]))
  return request.put(url, fd)
}

export const patchJSON = (url, data) =>
  request.patch(url, data, {
    headers: { 'Content-Type': 'application/json;charset=UTF-8' },
  })
export default request
export { baseURL }
